<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import * as apiUtil from "@/api/ApiUtils"
import {SelectOption} from "@/ts/CommonTypes";
import {Role,getDataScopeTypeList,save,getById} from "@/api/AuthRoleApi"

// Props 和 Emits
const props = defineProps<{
  dataId: number | null
}>();

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'successed'): void
}>();

/**
 * 表单数据
 */
const formData = ref<Role>(new Role())

/**
 * 数据验证规则
 */
const rules = {
  name: [{ required: true, message: "角色名称必填!" }],
  dataScope: [{ required: true, message: "数据权限范围必选!" }]
}

const dataScopeList = ref<SelectOption[]>([])

/**
 * 操作类型
 */
const actionType = computed(() => {
  return props.dataId ? "修改" : "添加"
})

/**
 * 页面加载后执行的钩子函数
 */
onMounted(() => {
  getDataScopeTypeList().then((res) => {
    if (apiUtil.isSuccessed(res)) {
      dataScopeList.value = res.data
      if (props.dataId) {
        handleGetDetail()
      } else {
        formData.value = new Role();
      }
    }
  })
})

/**
 * 保存数据
 */
const handleSave = async () => {
  try {
    const res = await save(formData.value)
    if (apiUtil.isSuccessed(res)) {
      emit('successed');
      emit('close');
      apiUtil.notifySuccess(`${actionType.value}成功`);
    }
  } catch (error) {
    emit('close');
    apiUtil.notifyError('提交失败',error.message);
  }
}

/**
 * 查询详情
 */
const handleGetDetail = async () => {
  if (!props.dataId) return;
  try {
    const res = await getById(props.dataId)
    if (apiUtil.isSuccessed(res)) {
      // 保留响应式连接的更新方式
      formData.value = res.data;
    }
  } catch (error) {
    apiUtil.notifyError('查询失败',error.message);
  }
}
</script>

<template>
  <div>
    <a-form
        :model="formData"
        name="basic"
        autocomplete="off"
        @finish="handleSave"
        :label-col="{ span: 3 }"
    >
      <a-form-item label="角色名称" name="name" :rules="rules.name">
        <a-input v-model:value="formData.name" />
      </a-form-item>

      <a-form-item label="角色描述" name="description">
        <a-input v-model:value="formData.description" />
      </a-form-item>

      <a-form-item label="权限范围" name="dataScope" :rules="rules.dataScope">
        <a-select v-model:value="formData.dataScope" :options="dataScopeList" />
      </a-form-item>

      <a-row>
        <a-col :offset="18" :span="3">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-col>
        <a-col>
          <a-button @click="emit('close')">取消</a-button>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<style scoped>
</style>
